<template>
    <span>
        <DownloadOutlined @click.stop="exportCode" />
        <my-icon v-if="item.icon" :type="item.icon"></my-icon>
        <a-badge v-if="enableVersion&&item.hasNew" status="processing" title="新接口" style="margin-bottom:3px;" />
        <span>{{item.name}}</span>
        <span v-if="item.num&&!collapsed" :class="item.menuClass" class="knife4j-menu-badge-num">{{item.num}}</span>
    </span>
</template>

<script>
import { useGlobalsStore } from '@/store/modules/global.js'
import { computed } from 'vue'
import { message } from 'ant-design-vue'
import { DownloadOutlined } from '@ant-design/icons-vue'
import "ant-design-vue/lib/message/style/index.less";

export default {
    components: {
        DownloadOutlined,
    },
    props: {
        item: Object,
        collapsed: {
            type: Boolean,
            default: false
        }
    },
    setup(props) {
        const appStore = useGlobalsStore()
        const { item } = props

        const exportCode = () => {
            function copyToClipboard(text) {
                const el = document.createElement('textarea'); // 创建一个临时的 textarea 元素
                el.value = text; // 设置文本内容
                el.setAttribute('readonly', ''); // 设置为只读以确保在移动设备上呈现虚拟键盘
                el.style.position = 'absolute';
                el.style.left = '-9999px'; // 移出屏幕可视区域
                document.body.appendChild(el); // 将元素添加到 DOM 中
                el.select(); // 选择文本内容
                document.execCommand('copy'); // 执行复制操作
                document.body.removeChild(el); // 复制完成后移除元素
            }
            copyToClipboard(getExportJSONData())
            message.success('复制到剪贴板');
        }

        const getExportJSONData = () => { //生成api代码段
            const paths = appStore.swaggerCurrentInstance.paths
            const pathsObj = {}
            paths.forEach(e => {
                pathsObj[e.url] = { query: e.originalApiInfo.parameters, body: e.originalApiInfo.requestBody }
            })
            let json = ''
            const commonPrefixStr = getCommonPrefixStr(item.children.map(e => e.url))
            item.children.forEach(e => {
                const index = e.url.lastIndexOf('/')
                const query = pathsObj[e.url].query
                const body = pathsObj[e.url].body
                //方法名
                const methodsName = e.url.slice(index + 1, e.url.leghth)
                //参数
                const params = (query?.map(e => e.name).join(', ') || '') + (query && body ? ', ' : '') + (body ? 'data' : '')
                //注释
                const annotation = e.name
                //请求方式
                const method = e.method
                //url
                const url = e.url.replace(commonPrefixStr, '')
                const queryPath = query?.map((e, index) => {
                    if (index === 0) {
                        return '?' + e.name + '=${' + e.name + '}'
                    } else {
                        return e.name + '=${' + e.name + '}'
                    }
                }).join('&')

                json += `    ${methodsName}(${params}) { //${annotation}\n        return http.${method.toLowerCase()}(\`\${prePath}${url}${queryPath || ''}\`${body ? ', data' : ''}).then(res => { return res.data })\n    },\n`
            })
            const path = item.path
            const { prefix, suffix } = httpTemplate(
                path.slice(path.indexOf('(') + 1, path.indexOf(')')) + commonPrefixStr,
                item.name
            )
            return prefix + json + suffix
        }

        const getCommonPrefixStr = (arr) => { //返回url公共前缀字符串
            const newArr = arr.map(e => e.split('/'))
            const firstItem = newArr[0]
            const indexArr = []
            newArr.forEach(e => {
                let maxSameIndex = 0
                for (let i = 0; i < e.length; i++) {
                    if (e[i] === firstItem[i]) {
                        maxSameIndex += 1
                    } else {
                        indexArr.push(maxSameIndex)
                        break
                    }
                }
            })
            const minIndex = Math.min(...indexArr)
            const commonStr = firstItem.splice(0, minIndex).join('/')
            return commonStr
        }

        const httpTemplate = (path, name) => {
            return {
                prefix: `import http from "@/utils/request"\nconst prePath = '/${path}'\n\n/**\n * ${name}\n **/\n\nconst api = {\n`,
                suffix: '}\n\nexport default api',
            }
        }

        return {
            enableVersion: computed(() => {
                return appStore.enableVersion;
            }),
            exportCode,
        }
    }
};
</script>

<style lang="less">
</style>